<?php
/**
 * 搜索关键词类
 *
 */
class Search_Word 
{
	const _CONST_DB_KEYS_        = 'search_keys';
	const _CONST_DBGRP_DEFAULT_  = 'default';
	const _CONST_DBGRP_READONLY_ = 'readonly';

	/**
	 * Chinese to Pinyin 
	 *
	 * @param	String	chinese
	 * @return	String
	 */
	public function chinese_2_pinyin ($chinese)
	{
		$p = new Pinyin;
		$pinyin = $p->translate($chinese);

		if (! empty($pinyin))
			$this->record_searched_word($pinyin, $chinese);

		return $pinyin;
	}

	/**
	 * Pinyin to Chinese (从词汇库里根据权重计算出)
	 *
	 * @param	String	pinyin
	 * @return	String
	 */
	public function pinyin_2_chinese ($pinyin, $policy = 'most')
	{
		$config= Kohana::config('cached.search_keys');
		$cache = Cache::instance(Arr::get($config, 'group', NULL));
		$key   = $config['key'] . $pinyin;
		$chs   = $cache->get($key);
		if ($chs === NULL)
		{
			$query = DB::select()
				->from(self::_CONST_DB_KEYS_)
				->where('tag', '=', $pinyin)
				->order_by('hits', "DESC")
				->limit(1)
				->execute(self::_CONST_DBGRP_READONLY_);
	
			if ($query->count() <= 0)
				$chs = '';
			else
			{
				$info = $query->current();
				$chs  = $info['skey'];
			}

			$life = $config['life'];
			$cache->set($key, $chs, $life);
		}
		
		return $chs;
	}

	/**
	 * record the word of seaching
	 */
	private function record_searched_word ($tag, $search_key)
	{
		$info = $this->word ($tag, $search_key);

		if (empty($info))
		{
			list($insert_id, $rows) = DB::insert(self::_CONST_DB_KEYS_)
				->columns (array('id', 'tag', 'skey', 'hits'))
				->values  (array(0, $tag, $search_key, 1))
				->execute (self::_CONST_DBGRP_DEFAULT_);
		}
		else
		{
			DB::update(self::_CONST_DB_KEYS_)
				->set(array('hits' => DB::expr('`hits`+1')))
				->where('id', '=', $info['id'])
				->execute(self::_CONST_DBGRP_DEFAULT_);
		}
	}

	private function word ($tag, $search_key)
	{
		$query = DB::select()
			->from(self::_CONST_DB_KEYS_)
			->where('tag', '=', $tag)
			->where('skey', '=', $search_key)
			->execute(self::_CONST_DBGRP_READONLY_);

		if ($query->count() > 0)
			return $query->current();
		else
			return NULL;
	}
}
